<template>
  <div style="overflow: auto">
    <el-button
      type="primary"
      style="float: left; margin-bottom: 10px"
      :size="size"
      @click="handleRefresh"
    >刷新</el-button>
    <el-button
      type="primary"
      v-if="!readonly"
      style="float: left; margin-bottom: 10px"
      :size="size"
      icon="fa fa-plus"
      @click="handleAdd"
    >新增</el-button>
    <el-button
      type="primary"
      v-if="!readonly"
      style="float: left; margin-bottom: 10px"
      :size="size"
      icon="fa fa-save"
      @click="saveTable"
    >保存</el-button
    >
    <el-table
      :data="tableData"
      style="width: 100%"
      :max-height="getTableMaxHeight()"
      v-loading="tableloading"
      :header-cell-style="{ background: 'rgba(117, 60, 202, 0.04)' }"
      :key="reftablerefresh"
      :size="size"
    >
      <el-table-column type="index" width="45"> </el-table-column>
      <el-table-column width="40" v-if="!readonly">
        <template slot-scope="scope">
          <i class="el-icon-delete icon_style" title="删除" @click="handleDelete(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column width="40" v-if="!readonly">
        <template slot-scope="scope">
          <i class="el-icon-sort icon_style" title="排序" @click="handSort(scope.row)"></i>
        </template>
      </el-table-column>
      <el-table-column prop="tableName" label="表名称" min-width="180"> </el-table-column>
      <el-table-column prop="tableCode" label="表" min-width="180"> </el-table-column>
      <el-table-column label="访视内显示名称" min-width="180" prop="visitTableName">
        <template slot-scope="scope">
          <el-input
            auto-complete="off"
            :title="scope.row.visitTableName"
            size="mini"
            style="width: 160px"
            v-model="scope.row.visitTableName"
            @change="changeinterviewName(scope.$index, scope.row, $event)"
            :disabled="readonly"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="date" label="关系类型" min-width="110">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.relationType"
            placeholder="请选择"
            size="mini"
            style="width: 90px"
            @change="changelookname(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >
            <el-option label="一对一" :value="1"></el-option>
            <el-option label="一对多" :value="2"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="映射表" min-width="180">
        <template slot-scope="scope">
          <el-input
            :title="scope.row.default"
            auto-complete="off"
            size="mini"
            v-model="scope.row.default"
            style="width: 110px"
            disabled
          ></el-input>
          <el-button
            size="mini"
            style="width: 40px; margin-left: 2px"
            @click="defaultNum(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >...</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="modification" label="需隐藏变量" min-width="180">
        <template slot-scope="scope">
          <el-input
            :title="scope.row.hiddenvariable"
            auto-complete="off"
            size="mini"
            v-model="scope.row.hiddenvariable"
            style="width: 110px"
            disabled
          ></el-input>
          <el-button
            size="mini"
            style="width: 40px; margin-left: 2px"
            @click="hiddenNum(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >...</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="modification" label="优先填写" min-width="90">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.priority"
            placeholder="请选择"
            size="mini"
            style="width: 70px"
            @change="changelookname(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >
            <el-option label=" " :value="0"></el-option>
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="2"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="modification" label="不可见角色" min-width="180">
        <template slot-scope="scope">
          <el-input
            :title="scope.row.Invisiblerole"
            auto-complete="off"
            size="mini"
            v-model="scope.row.Invisiblerole"
            style="width: 110px"
            disabled
          ></el-input>
          <el-button
            size="mini"
            style="width: 40px; margin-left: 2px"
            @click="Rolebtn(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >...</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="modification" label="设置未发生" min-width="90">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.notOccurred"
            placeholder="请选择"
            size="mini"
            style="width: 70px"
            @change="changelookname(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="2"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="modification" label="设置未采集" min-width="90">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.notCollected"
            placeholder="请选择"
            size="mini"
            style="width: 70px"
            @change="changelookname(scope.$index, scope.row, $event)"
            :disabled="readonly"
          >
            <el-option label="是" :value="1"></el-option>
            <el-option label="否" :value="2"></el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>

    <!-- 排序 -->
    <el-dialog title="排序" width="500px" :visible.sync="openSort">
      <el-form label-width="160px" style="text-align: left" :size="size">
        <el-form-item label="目标顺序：">
          <el-select v-model="targetId" placeholder="请选择" filterable clearable>
            <el-option v-for="item in tableData" :key="item.id" :label="item.tableName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :size="size" @click.native="openSort = false">取消</el-button>
        <el-button :size="size" type="primary" @click.native="submitSort">提交</el-button>
      </div>
    </el-dialog>

    <!-- 需隐藏变量 -->
    <el-dialog width="600px" :visible.sync="dialoghidden" :close-on-click-modal="false">
      <el-button style="float: left; margin-bottom: 10px" :size="size" type="primary" @click="needHidden"
      >确认</el-button
      >
      <el-table
        ref="multipleTable_hide"
        :data="visitTableFieldList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="hiddenSelectionChange"
        v-loading="editloading"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column type="index" label="序号" width="120"> </el-table-column>
        <el-table-column prop="fieldKey" label="变量" width="120"> </el-table-column>
        <el-table-column prop="fieldName" label="变量名" show-overflow-tooltip> </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 不可见角色 -->
    <el-dialog width="600px" :visible.sync="dialogvisic" :close-on-click-modal="false">
      <el-button style="float: left; margin-bottom: 10px" :size="size" type="primary" @click="Affirm">确认</el-button>
      <el-table
        ref="multipleTable_role"
        :data="RoleList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="invisibleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="code" label="角色" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="name" label="角色名称" show-overflow-tooltip> </el-table-column>
      </el-table>
    </el-dialog>
    <addVisit
      :dialogVisible="dialogVisible"
      :tableData="tableData"
      :DatabaseCrfList="DatabaseCrfList"
      :edcBuildProjectId="edcBuildProjectId"
      :edcDataBaseId="edcDataBaseId"
      :dataBaseVersion="dataBaseVersion"
      :environment="environment"
      @addVisitCancal="addVisitCancal"
      @addVisitOk="addVisitOk"
    ></addVisit>
    <defaultNum
      :dialogdefaultNum="dialogdefaultNum"
      :defaultNumIndex="defaultNumIndex"
      :orignDefaultValues="orignDefaultValues"
      :visitTableFieldList="visitTableFieldList"
      @defaultCancal="defaultCancal"
      @defaultOk="defaultOk"
    ></defaultNum>
  </div>
</template>

<script>
import addVisit from './component/add-visit.vue'
import defaultNum from './component/default-num.vue'
import { mapActions } from 'vuex'

export default {
  components: {
    addVisit,
    defaultNum,
  },
  data() {
    return {
      reftablerefresh: 0,
      defaultNumForm: {
        name: '',
      },
      openSort: false,
      targetId: '',
      size: 'mini',
      optionId: '',
      tableloading: false,
      disabledSubmit: false,
      dialogVisible: false,
      multipleSelection: [], // 批量新增时选择的表单
      tableData: [], // 表单列表
      edcDataBaseId: '',
      dialogdefaultNum: false,
      defaultNumSelection: [], // 选择的默认值列表
      dialoghidden: false,
      dialogvisic: false,
      hiddenSelection: [], // 选择的需隐藏的变量列表
      invisibleSelection: [], // 选择的不可见角色列表
      edcBuildProjectId: '',
      DatabaseCrfList: [], // 所有可选表单
      tableList: [], // 新增时选择的表单请求数据
      RoleList: [], // 角色列表
      defaultNumId: '',
      type: '',
      defaultNumIndex: null,
      visitTableFieldList: [],
      editloading: false,
      dataBaseVersion: '',
      orignDefaultValues: [],
      environment: '',
      readonly: false, // 页面是否只读的标识
    }
  },
  mounted() {
    const databaseInfo = JSON.parse(localStorage.getItem('sys-database-info')) || {}

    if (databaseInfo.isLock === '1') {
      this.readonly = true
    }

    this.edcBuildProjectId = localStorage.getItem('sys-project-id') || ''
    this.edcDataBaseId = databaseInfo.databaseId || ''
    this.dataBaseVersion = databaseInfo.databaseVersion || ''

    this.environment = sessionStorage.getItem('environment') || '0'
    this.findPage()

    this.edcRole()
    window.addEventListener('resize', () => {
      this.getTableMaxHeight()
      this.$forceUpdate()
    })
  },
  methods: {
    ...mapActions('eCRFDesign', ['qryDesignList']),
    ...mapActions('visitDesign', [
      'visitTableList',
      'visitTableDelete',
      'visitTableUpdate',
      'visitTableFieldSelect',
      'roleQuery',
      'visitTableSortChange'
    ]),
    // 表格自适应屏幕高度
    getTableMaxHeight() {
      return document.documentElement.clientHeight - 200
    },
    // 不可见角色弹框
    Rolebtn(index, data, event) {
      this.dialogvisic = true
      this.unvisiableRoleIndex = index
      // 回显已勾选的角色
      const orignRoles = data.exculdeRoles
      this.$nextTick(() => {
        this.$refs.multipleTable_role.clearSelection()
        if (orignRoles != null && orignRoles.length > 0) {
          for (const role of orignRoles) {
            // 角色列表勾选
            for (const one of this.RoleList) {
              if (role.roleId === one.onlyId) {
                this.$refs.multipleTable_role.toggleRowSelection(one, true)
              }
            }
          }
        }
      })
    },

    // 刷新列表数据
    handleRefresh() {
      this.findPage()
    },

    // 获取可批量增加的表单列表
    getDatabaseCrf() {
      const params = {
        projectId: this.edcBuildProjectId,
        databaseId: this.edcDataBaseId,
        databaseVersion: this.dataBaseVersion,
        environment: this.environment,
        embedded: '0',
      }
      this.qryDesignList({ params }).then(res => {
        const { data, code } = res
        if (code === 200) {
          for (const val of res.data) {
            val.number = 1
          }
          data.map((dItem, dIndex) => {
            if (dItem.surface !== 'SUBJECT') {
              this.DatabaseCrfList.push(dItem)    
            }
          })
        } else {
          this.DatabaseCrfList = []
        }
      })
    },
    //  不可见角色多选
    invisibleSelectionChange(val) {
      this.invisibleSelection = val
    },
    // 不可见角色确认
    Affirm() {
      this.dialogvisic = false
      const rolsname = []
      for (const val of this.invisibleSelection) {
        rolsname.push(val.code)
      }
      const rols = []
      this.invisibleSelection.forEach(item => {
        rols.push(item.id)
      })
      this.tableData[this.unvisiableRoleIndex].Invisiblerole = rolsname.join(',')
      this.tableData[this.unvisiableRoleIndex].roleIds = rols
      this.reftablerefresh++
    },
    // 获取edc角色
    edcRole: function () {
      const params = {
        projectId: this.edcBuildProjectId,
        type: 1,
      }
      this.roleQuery({ params }).then(res => {
        if (res.code === 200) {
          this.RoleList = res.data.records
        }
      })
    },

    defaultCancal() {
      this.dialogdefaultNum = false
    },

    defaultOk(value) {
      this.dialogdefaultNum = false
      console.log('value', value)
      this.tableData.forEach((item, index) => {
        if (index === value.defaultNumIndex) {
          this.$set(item, 'default', value.def.join(';'))
          this.$set(item, 'defaultValues', value.defName)
        }
      })


      this.reftablerefresh++
    },
    // 默认值弹框
    defaultNum(index, data, event) {
      this.defaultNumIndex = index
      this.dialogdefaultNum = true
      this.defaultNumId = data.id
      this.type = 1
      this.getdefaultNum()
      this.orignDefaultValues = this.tableData[this.defaultNumIndex].defaultValues
    },

    // 获取默认值数据
    getdefaultNum() {
      this.editloading = true
      const params = {
        id: this.defaultNumId,
        type: this.type,
        projectId: this.edcBuildProjectId,
        databaseVersion: this.dataBaseVersion,
        databaseId: this.edcDataBaseId,
        environment: this.environment,
      }
      this.visitTableFieldSelect({ params }).then(res => {
        if (res.code === 200) {
          // 回显默认值变量
          if (this.type === 1) {
            for (const record of res.data) {
              record.defaultnumber = ''
            }
            this.visitTableFieldList = res.data
          } else if (this.type === 2) {
            // 回显隐藏的变量
            this.visitTableFieldList = res.data
            const orignHideFields = this.tableData[this.hiddenNumIndex].hideFields || []
            this.$nextTick(() => {
              this.$refs.multipleTable_hide.clearSelection()
              if (orignHideFields != null && orignHideFields.length > 0) {
                for (const role of orignHideFields) {
                  // 角色列表勾选
                  for (const one of this.visitTableFieldList) {
                    console.log('one', role, one)
                    if (role.tableField === one.fieldKey) {
                      this.$refs.multipleTable_hide.toggleRowSelection(one, true)
                    }
                  }
                }
              }
            })
          }
        }
        this.editloading = false
      })
    },
    // 需隐藏变量的弹框
    hiddenNum(index, data, event) {
      this.hiddenNumIndex = index
      this.dialoghidden = true
      this.defaultNumId = data.id
      this.type = 2
      this.getdefaultNum()
    },
    // 需隐藏变量的弹框
    hiddenSelectionChange(val) {
      this.hiddenSelection = val
    },
    // 需隐藏变量的确认按钮
    needHidden() {
      this.dialoghidden = false
      const hid = []
      for (const val of this.hiddenSelection) {
        hid.push(val.fieldName)
      }
      const hidId = []
      this.hiddenSelection.forEach(item => {
        hidId.push(item.fieldKey)
      })
      // this.hidId = hidId
      this.tableData[this.hiddenNumIndex].hiddenvariable = hid.join(',')
      this.tableData[this.hiddenNumIndex].hideFields = hidId
      // console.log(this.tableData[this.hiddenNumIndex]);
      this.reftablerefresh++
    },
    // 访视内显示的名称
    changeinterviewName(index, data, event) {
      this.tableData[index].visitTableName = event
    },
    // 保存按钮
    saveTable() {
      const savelist = []
      for (const data of this.tableData) {
        console.log('11111111', data)
        savelist.push({
          id: data.id,
          visitTableName: data.visitTableName,
          relationType: data.relationType,
          priority: data.priority,
          notOccurred: data.notOccurred,
          notCollected: data.notCollected,
          excludeRoleIds: data.roleIds, // 不可见角色id
          hiedFields: data.hidIds,
          defaultFields: data.defaultValues,
        })
        this.seaveList = savelist
      }
      const data = {
        databaseId: this.edcDataBaseId,
        databaseVersion: this.dataBaseVersion,
        updateDataList: this.seaveList,
        projectId: this.edcBuildProjectId,
        environment: this.environment,
      }
      this.visitTableUpdate({ data })
        .then(resp => {
          if (resp.code === 200) {
            this.$message({
              type: 'success',
              message: '保存成功',
            })
            this.findPage()
          }
        })
        .catch(resp => {
          this.$message({
            type: 'info',
            message: '保存失败，' + resp.message,
          })
        })
    },

    addVisitOk() {
      this.dialogVisible = false
      this.DatabaseCrfList = []
      this.findPage()
    },

    addVisitCancal() {
      this.DatabaseCrfList = []
      this.dialogVisible = false
    },

    // table改变值
    changelookname(index, row, event) {},
    // 排序
    handSort(data) {
      this.openSort = true
      this.targetId = data.id
      this.optionId = data.id
    },
    // 排序提交
    submitSort() {
      if (this.targetId === '') {
        this.$message({
          type: 'error',
          message: '请选择目标顺序！',
        })
        return
      }
      if (this.optionId === this.targetId) {
        this.$message({
          type: 'error',
          message: '请选择与节点不同的目标节点！',
        })
        return
      }
      this.openSort = false
      const data = {
        optionId: this.optionId,
        targetId: this.targetId,
      }
      this.visitTableSortChange({ data }).then(res => {
        if (res.code === 200) {
          this.findPage()
          this.$message({
            type: 'success',
            message: '排序成功',
          })
        }
      })
    },
    // 增加
    handleAdd() {
      this.getDatabaseCrf()
      this.dialogVisible = true
      for (const item of this.DatabaseCrfList) {
        item.number = 1
      }
    },
    // 删除
    handleDelete(row) {
      const params = {
        id: row.id,
      }
      this.$confirm('确认删除吗？', '提示', { type: 'warning' }).then(() => {
        this.visitTableDelete({ params }).then(res => {
          if (res.code === 200) {
            this.findPage()
            this.$message({
              message: '删除成功',
              type: 'success',
            })
          }
        })
      })
    },
    // 获取数据
    findPage() {
      this.tableloading = true
      const params = {
        databaseId: this.edcDataBaseId,
        databaseVersion: this.dataBaseVersion,
        projectId: this.edcBuildProjectId,
        environment: this.environment,
      }
      this.visitTableList({ params }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data

          this.tableData.forEach(item => {
            // 渲染隐藏变量
            const hid = [] // 变量字段
            const hidNames = [] // 变量名称
            item.hideFields &&
              item.hideFields.forEach(el => {
                hid.push(el.tableField)
                hidNames.push(el.tableFieldName)
              })
            item.hidIds = hid
            item.hiddenvariable = hidNames.join(',')
            // 渲染默认值
            const dif = [] // 默认值字段
            const defaultval = [] // 默认值字段的值
            item.defaultValues &&
              item.defaultValues.forEach(el => {
                dif.push({
                  fieldValue: el.fieldValue,
                  tableField: el.tableField,
                })
                defaultval.push(el.tableFieldName + ':' + el.fieldValueName)
              })
            item.defaultValues = dif
            item.default = defaultval.join(';')
          })

          // }
        }
        this.tableloading = false
      })
    },
  },
}
</script>

<style></style>
